﻿using Microsoft.Win32;
using StudentInfoSystem.Core.Data.DbContexts;
using StudentInfoSystem.Core.Models;
using StudentInfoSystem.Core.Utils;
using System.IO;
using System.Windows;

namespace StudentInfoSystem.UI.Views.Component
{
    public partial class GenerateDataWindow : Window
    {
        public string DatabasePath { get; private set; } = string.Empty;

        public GenerateDataWindow()
        {
            InitializeComponent();
        }

        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            if (!int.TryParse(CountTextBox.Text, out int count) || count <= 0)
            {
                MessageBox.Show("请输入有效的生成数量", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            string fileName = FileNameTextBox.Text;
            if (string.IsNullOrWhiteSpace(fileName))
            {
                MessageBox.Show("请输入有效的文件名", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (!fileName.EndsWith(".db"))
            {
                fileName += ".db";
            }

            // 确定保存路径
            string savePath;
            if (UseDefaultPathCheckBox.IsChecked == true)
            {
                // 使用默认路径 (程序目录/Data/)
                string appDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
                string dataDirectory = Path.Combine(appDirectory, "Data");

                if (!Directory.Exists(dataDirectory))
                {
                    Directory.CreateDirectory(dataDirectory);
                }

                savePath = Path.Combine(dataDirectory, fileName);
            }
            else
            {
                // 让用户选择保存位置
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    Filter = "SQLite 数据库文件 (*.db)|*.db",
                    FileName = fileName
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    savePath = saveFileDialog.FileName;
                }
                else
                {
                    return; // 用户取消了选择
                }
            }

            // 生成数据
            try
            {
                var students = StudentDataGenerator.GenerateRandomStudents(count);

                // 创建新数据库并保存数据
                using (var context = new AppDbContext($"Data Source={savePath}"))
                {
                    context.Database.EnsureCreated(); // 确保数据库和表存在

                    // 清空现有数据（如果表已存在）
                    var allStudents = context.Students.ToList();
                    context.Students.RemoveRange(allStudents);
                    context.SaveChanges();

                    context.Students.AddRange(students);
                    context.SaveChanges();
                }

                DatabasePath = savePath;

                // 询问是否加载新数据库
                var result = MessageBox.Show($"已成功生成 {count} 条学生数据到:\n{savePath}\n\n是否加载此数据库文件?",
                                           "生成成功", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    DialogResult = true;
                }
                else
                {
                    DialogResult = false;
                }

                Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show($"生成数据时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }
}